package com.binance.assetservice.web.controller;

import com.binance.assetservice.api.ISymbolRealtimeApi;
import com.binance.assetservice.vo.request.symbolrealtime.GetClosePriceRequest;
import com.binance.assetservice.vo.response.symbolrealtime.GetClosePriceResponse;
import com.binance.assetservice.web.service.IOrderBookManagerService;
import com.binance.assetservice.web.service.IProductService;
import com.binance.master.models.APIRequest;
import com.binance.master.models.APIResponse;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.javasimon.aop.Monitored;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@RestController
@Monitored
public class SymbolRealtimeController implements ISymbolRealtimeApi {

    @Resource
    private IOrderBookManagerService orderBookManagerService;
    @Resource
    private IProductService productService;

    @Override
    public APIResponse<List<GetClosePriceResponse>> getClose(
            @RequestBody @Validated APIRequest<GetClosePriceRequest> request) {
        List<GetClosePriceResponse> list = Lists.newArrayList();
        String s = request.getBody().getSymbol();
        if (StringUtils.isNoneBlank(s)) {
            GetClosePriceResponse resp = new GetClosePriceResponse();
            resp.setSymbol(s);
            resp.setPrice(BigDecimal.valueOf(this.orderBookManagerService.getClose(s)));
            list.add(resp);
        } else {
            List<String> symbols = this.productService.getVisibleSymbols();
            if (CollectionUtils.isNotEmpty(symbols)) {
                for (String symbol : symbols) {
                    GetClosePriceResponse resp = new GetClosePriceResponse();
                    resp.setSymbol(symbol);
                    resp.setPrice(BigDecimal.valueOf(this.orderBookManagerService.getClose(symbol)));
                    list.add(resp);
                }
            }
        }
        return APIResponse.getOKJsonResult(list);
    }

}
